﻿/*-----------------------------------------------------------------------
 * <copyright file="OPEntryScoreQueryControl.xaml.cs" company="O-RID">
 *     Copyright (c)2010 O-RID Co.,Ltd.
 * </copyright>
 * <author>Zhang jun</author>
 * <summary>
 *           OP 总成绩查询
 *     引用服务：WCFServers.OPQueryRef
 *     服务功能：OP成绩查询
 *    
 *     引用服务：WCFLog4Ref.WCFLog4Client
 *     服务功能：记录日志
 * 
 * (界面)StackPanel的控件名和TextBox控件名相同
 *       Button与StackPanel的名称相同
 *       
 *  作成日：06/11/2010
 *          09/28/0210 增加 分页记录数可自定义
 *          10/14/2010 修改 导出功能异常
 *          10/18/2010 修改 点击标题头排序时，导出内容不是排序结果的问题。
 * </summary>
 *----------------------------------------------------------------------- 
 */

namespace Orid.Management.Statistics.OperatorUnitMangement.ScoreRelated.OPEntryScoreQuery
{
    using System;
    using System.Threading;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Media;
    using Orid.Management.Statistics.OperatorUnitMangement.Common.Export;
    using Orid.Management.Statistics.OperatorUnitMangement.Common.FunctionList;
    using Orid.Management.Statistics.OperatorUnitMangement.Common.SearchCtrl;
    using Orid.Management.Statistics.OperatorUnitMangement.WCFLog4Ref;
    using Orid.Management.Statistics.OperatorUnitMangement.WCFServers.OPQueryRef;
    using childWindow = Orid.Management.Statistics.OperatorUnitMangement.Common.Window;
    using Command = Orid.Management.Statistics.OperatorUnitMangement.Command;
    using Wcf = Orid.Management.Statistics.OperatorUnitMangement.Common.Service;

    /// <summary>
    ///  OP成绩查询
    ///  OPEntryScoreQueryControl
    /// </summary>
    public partial class OPEntryScoreQueryControl : UserControl
    {
        #region 全局变量
        /// <summary>
        /// 当前查询框的名字（日志用）
        /// </summary>
        private string ctrlName = " OP总成绩 ";

        /// <summary>
        /// 查询区域对象
        /// SelAnyContainer
        /// </summary>
        private SelAnyContainer selanyContainer;
               
        /// <summary>
        /// 日志服务定义
        /// WCFLog4Client
        /// </summary>
        private WCFLog4Client wcfLogClient;
        
        /// <summary>
        /// 查询子窗体
        /// OPIDSelectChildWindow
        /// </summary>
        private childWindow.OPIDSelectChildWindow opidSelect;
                
        /// <summary>
        /// 消息子窗体
        /// errorMessbox
        /// </summary>
        private childWindow.MessageBox errorMessbox;
        
        /// <summary>
        /// 分页控件
        /// PagedCollectionView
        /// </summary>
        private PagedCollectionView pcv;

        /// <summary>
        /// 记录要导出的数据
        /// DataGrid
        /// </summary>
        private DataGrid dataToCSV;

        /// <summary>
        /// 记录总数
        /// </summary>
        /// <value>10/18/2010 Add 排序导出用</value>
        private int sumRecordCount = 0;

        /// <summary>
        /// 记录NumericUpDown分页数
        /// </summary>
        /// <value>10/18/2010 Add 排序导出用</value>
        private double oldNumericUpDown = 0;

        #endregion 全局变量

        /// <summary>
        /// 构造函数
        /// OPEntryScoreQueryControl
        /// </summary>
        /// <param name="selanyContainer">查询区域对象 SelAnyContainer</param>
        public OPEntryScoreQueryControl(SelAnyContainer selanyContainer)
        {
            InitializeComponent();

            // 引用主题
            ((App)Application.Current).SetTheme((Grid)LayoutRoot);
            this.dgOPScoreQuery.HeadersVisibility = DataGridHeadersVisibility.All;//同时显示DataGrid的行头与列头

            this.selanyContainer = selanyContainer;
            this.wcfLogClient = Wcf.Service.Log4;
            this.opidSelect = new childWindow.OPIDSelectChildWindow();
            this.errorMessbox = new childWindow.MessageBox();
            this.dataToCSV = new DataGrid();

            #region 查询设置
            Command.OP.OPScoreQuery queryCommand = new Command.OP.OPScoreQuery(selanyContainer);

            queryCommand.ExecOver += new EventHandler<SelectOPScoreCompletedEventArgs>(this.WCFOPScoreClient_SelectOPScoreCompleted);

            queryCommand.ExecBegin += new EventHandler<EventArgs>(this.QueryCommand_ExecBegin);

            this.selanyContainer.QueryCcommand = queryCommand;

            #endregion 查询设置

            #region 导出设置
            //导出
            Command.DateExport exportCommand = new Command.DateExport();
            //导出开始
            exportCommand.ExecBegin += new EventHandler<EventArgs>(this.ExportCommand_ExecBegin);

            this.selanyContainer.ExportComand = exportCommand;

            #endregion 导出设置

            //设置 查询界面 的 查询按钮 数据导出 初始化可用
            this.selanyContainer.btnSelect.IsEnabled = true;
            this.selanyContainer.btnExport.IsEnabled = true;
            this.selanyContainer.btnExport.Margin = new Thickness(90, 0, 0, 0);
            this.nuPageSize.IsEnabled = true; //分页数量 09/28/2010 Add

            // 设置背景色
            LayoutRoot.Background = new SolidColorBrush(Color.FromArgb(255, 243, 244, 245));


        }

        /// <summary>
        /// 查询开始
        /// 显示busybar
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of EventArgs</param>
        private void QueryCommand_ExecBegin(object sender, EventArgs e)
        {
            this.SetBusyBar(100);
        }


        #region 查询符合条件的OP信息
  
        /// <summary>
        /// 查询符合条件的OP信息(查询按钮)
        /// WCFOPScoreClient_SelectOPScoreCompleted
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of SelectOPScoreCompletedEventArgs</param>
        private void WCFOPScoreClient_SelectOPScoreCompleted(object sender, SelectOPScoreCompletedEventArgs e)
        { 
            try
            {
                //设置 查询界面 的 查询按钮 可用
                this.selanyContainer.btnSelect.IsEnabled = true;

                if (e.Error == null)
                {
                    if (e.Result.Count > 0)
                    {
                        //记录所查询的记录总数（导出结果与排序内容一致用）
                        this.sumRecordCount = e.Result.Count;

                        this.pcv = new PagedCollectionView(e.Result);
                        this.pcv.PageSize = Convert.ToInt32(this.nuPageSize.Value);

                        this.dataToCSV.ItemsSource = null;
                        this.dataToCSV.ItemsSource = e.Result;

                        this.dgOPScoreQuery.ItemsSource = this.pcv;
                        this.dpDataPage.DataContext = this.pcv;
 
                        Dispatcher.BeginInvoke(() => DataContext = false);
                        this.nuPageSize.IsEnabled = true; //分页数量 09/28/2010 Add

                        this.wcfLogClient.InfoAsync(((App)Application.Current).LogStr +
                                                        "在 " + this.ctrlName + " 查询中查询记录" +
                                                        selanyContainer.WhereIntorLogs );
                    }
                    else
                    {
                        this.dgOPScoreQuery.ItemsSource = null;
                        this.dpDataPage.DataContext = null;
                        this.dataToCSV = null;

                        throw new Exception(this.ctrlName + " 查询中没有可显示的OP数据");
                    }
                }
                else 
                {
                    throw (new Exception("OPEntryScoreQueryControl服务返回值有错" + e.Error.Message.ToString()));
                }
            }
            catch (Exception exce)
            {
                string exceptionStr = FunctionClass.GetMessageInformation(exce);

                Dispatcher.BeginInvoke(() => DataContext = false);
                this.nuPageSize.IsEnabled = true; //分页数量 09/28/2010 Add

                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr + 
                                                    ctrlName +
                                                    exceptionStr +
                                                    selanyContainer.WhereIntorLogs);
                FunctionClass.ShowMessageBox(
                    this.errorMessbox,
                    1,
                   "提示",
                   exceptionStr,
                   Colors.Gray,
                   true,
                   Visibility.Visible,
                   Visibility.Collapsed);
                return;
            }
        }

        #endregion 查询符合条件的OP信息(查询按钮)

        #region BusyBar

        /// <summary>
        /// 让BusyBar开始
        /// SetBusyBar
        /// </summary>
        /// <param name="busySeconds">busyBar 显示时间 ms</param>
        private void SetBusyBar(int busySeconds)
        {
            int delayMilliseconds = 2;
            biBusyBar.DisplayAfter = TimeSpan.FromMilliseconds(delayMilliseconds);
          
            DataContext = true;
            this.nuPageSize.IsEnabled = false; //分页数量 09/28/2010 Add
            ThreadPool.QueueUserWorkItem((state) =>
            {
                Thread.Sleep(busySeconds * 1000); 
            });
        }
        #endregion BusyBar

        #region 数据导出

        /// <summary>
        /// 导出开始
        /// ExportCommand_ExecBegin
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of EventArgs</param>
        private void ExportCommand_ExecBegin(object sender, EventArgs e)
        {
            this.ExportDate();
        }

        /// <summary>
        /// 导出 按钮  
        /// ExportDate
        /// </summary>        
        private void ExportDate()
        {
            try
            { 
                //设置 查询界面 的 数据导出 可用
                this.selanyContainer.btnExport.IsEnabled = true;

                if (this.dgOPScoreQuery.ItemsSource == null)
                {
                    throw new Exception("请查询后再将数据导出。");
                }
                else
                {
                    //导出结果与排序内容一致用
                    this.oldNumericUpDown = this.nuPageSize.Value;
                    this.pcv.PageSize = this.sumRecordCount;
                    this.dataToCSV.ItemsSource = this.pcv;

                    this.ExportDataToFile(this.dgOPScoreQuery);
                }
            }
            catch (Exception ex) 
            {

                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr +
                                                    " ExportDate(" + this.ctrlName + ") " + 
                                                    ex.Message.ToString() +
                                                    selanyContainer.WhereIntorLogs);
                FunctionClass.ShowMessageBox(
                    this.errorMessbox,
                    1,
                    "提示",
                   ex.Message.ToString(),
                   Colors.Gray,
                   true,
                   Visibility.Visible,
                   Visibility.Collapsed);
                return;
            }
        }

        /// <summary>
        /// 数据导出
        /// ExportDataToFile
        /// </summary>
        /// <param name="grid">带有显示格式的 grid</param>
        /// <value>10/14/2010 修改 导出功能异常</value>
        private void ExportDataToFile(DataGrid grid)
        {
            try
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.DefaultExt = "csv";
                sfd.Filter = "CSV Files (*.csv)|*.csv|All files (*.*)|*.*";

                sfd.FilterIndex = 1;
                bool? ret = sfd.ShowDialog();
                if (ret == true)
                {
                    string data = DataExport.ExportDataGrid(true, grid, this.dataToCSV, null);

                    using (System.IO.Stream stream = sfd.OpenFile())
                    {
                        using (System.IO.StreamWriter writer = new System.IO.StreamWriter(stream, System.Text.UnicodeEncoding.Unicode))
                        {
                            //由 逗号 换成 ^ ,--07/30/2010--EIDT 修改 千分位分割符用TAB替换问题
                            data = data.Replace("^", "\t");
                            writer.Write(data);
                            writer.Close();
                        }

                        stream.Close();
                    }
                    this.pcv.PageSize = Convert.ToInt32(this.oldNumericUpDown);
                    this.wcfLogClient.InfoAsync(((App)Application.Current).LogStr +
                                                    "在 " + this.ctrlName + "查询中导出记录" +
                                                    selanyContainer.WhereIntorLogs);

                    FunctionClass.ShowMessageBox(
                      this.errorMessbox,
                      0,
                     "提示",
                     "数据已导出。",
                     Colors.Gray,
                     true,
                     Visibility.Visible,
                     Visibility.Collapsed);
                    return;
                }
                else
                {
                    this.pcv.PageSize = Convert.ToInt32(this.oldNumericUpDown);
                    return;
                }
            }
            catch (Exception ex)
            {
                this.pcv.PageSize = Convert.ToInt32(this.oldNumericUpDown);
                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr +
                                                " ExportDataToFile(" + this.ctrlName + ")" + 
                                                ex.Message.ToString() +
                                                selanyContainer.WhereIntorLogs);
                FunctionClass.ShowMessageBox(
                    this.errorMessbox,
                    1,
                   "提示",
                   ex.Message.ToString(),
                   Colors.Gray,
                   true,
                   Visibility.Visible,
                   Visibility.Collapsed);
                return;
            }
        }

        #endregion 数据导出
        
    }
}
